use sea_orm_migration::prelude::*;

use crate::m20240806_000001_create_account_group::AccountGroup;

pub struct Migration;

impl MigrationName for Migration {
    fn name(&self) -> &str {
        "m20240806_000001_create_user_table"
    }
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    // Define how to apply this migration: Create the table.
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(User::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(User::Id).big_integer().primary_key())
                    .col(
                        ColumnDef::new(User::AccountGroupId)
                            .big_integer()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(User::Username)
                            .string_len(50)
                            .not_null()
                            .unique_key(),
                    )
                    .col(ColumnDef::new(User::Password).string_len(100).not_null())
                    .col(ColumnDef::new(User::FullName).string_len(50).not_null())
                    .col(ColumnDef::new(User::AvatarFilename).string_len(200))
                    .col(ColumnDef::new(User::Description).string_len(200))
                    .col(ColumnDef::new(User::AuthFailedAttempt).integer())
                    .col(ColumnDef::new(User::Enabled).boolean().default(true))
                    .col(
                        ColumnDef::new(User::AccountExpired)
                            .boolean()
                            .default(false),
                    )
                    .col(ColumnDef::new(User::AccountLocked).boolean().default(false))
                    .col(
                        ColumnDef::new(User::PasswordExpired)
                            .boolean()
                            .default(false),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_user_account_group")
                            .from(User::Table, User::AccountGroupId)
                            .to(AccountGroup::Table, AccountGroup::Id),
                    )
                    .to_owned(),
            )
            .await
    }

    // Define how to rollback this migration: Drop the table.
    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(User::Table).to_owned())
            .await
    }
}

#[derive(Iden)]
pub enum User {
    Table,
    Id,
    AccountGroupId,
    Username,
    Password,
    FullName,
    AvatarFilename,
    Description,
    AuthFailedAttempt,
    Enabled,
    AccountExpired,
    AccountLocked,
    PasswordExpired,
}
